package com.lemon.reggie.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lemon.reggie.common.BusinessException;
import com.lemon.reggie.pojo.dto.AddCartDTO;
import com.lemon.reggie.pojo.dto.SubCartDTO;
import com.lemon.reggie.pojo.entity.ShoppingCart;
import com.lemon.reggie.mapper.ShoppingCartMapper;
import com.lemon.reggie.pojo.vo.ShoppingCartVO;
import com.lemon.reggie.service.ShoppingCartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lemon.reggie.utils.BaseContextUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 * 购物车 服务实现类
 * </p>
 *
 * @author Lemon
 * @since 2022-05-23
 */
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {

    /**
     * 添加购物车
     * @param addCartDTO
     * @return void
     * @author Guannankun
     * @since 2022/8/22
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addCart(AddCartDTO addCartDTO) {
        ShoppingCart one = null;
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<ShoppingCart>()
                .eq(ShoppingCart::getUserId, BaseContextUtil.getCurrentId());

        if (Objects.nonNull(addCartDTO.getDishId())) {
            //菜品
            wrapper.eq(ShoppingCart::getDishId, addCartDTO.getDishId())
                    .eq(StrUtil.isNotBlank(addCartDTO.getDishFlavor()),
                    ShoppingCart::getDishFlavor, addCartDTO.getDishFlavor());
            one= this.getOne(wrapper);

        } else {
            //套餐
            wrapper.eq(ShoppingCart::getSetmealId, addCartDTO.getSetmealId());
            one = this.getOne(wrapper);
        }


        if (Objects.isNull(one)) {
            //如果当前用户首次添加此菜品，设置数量为1，insert操作
            one = new ShoppingCart();
            BeanUtil.copyProperties(addCartDTO, one);
            one.setUserId(BaseContextUtil.getCurrentId());
            this.save(one);
        } else {
            //如果当前用户已添加此菜品，数量就+1，update操作
            one.setNumber(one.getNumber() + 1);
            this.updateById(one);
        }
    }

    /**
     * 获取当前用户购物车
     * @return java.util.List<com.lemon.reggie.pojo.vo.ShoppingCartVO>
     * @author Guannankun
     * @since 2022/8/22
     */
    @Override
    public List<ShoppingCartVO> listCart() {
        List<ShoppingCart> list = this.list(new LambdaQueryWrapper<ShoppingCart>()
                .eq(ShoppingCart::getUserId, BaseContextUtil.getCurrentId())
                .orderByDesc(ShoppingCart::getCreateTime));

        if (CollUtil.isNotEmpty(list)) {
            return list.stream().map(shoppingCart -> {
                ShoppingCartVO shoppingCartVO = new ShoppingCartVO();
                BeanUtil.copyProperties(shoppingCart, shoppingCartVO);
                return shoppingCartVO;
            }).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    /**
     * 减少购物车中的商品
     * @param subCartDTO
     * @return void
     * @author Guannankun
     * @since 2022/8/23
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void subCart(SubCartDTO subCartDTO) {
        ShoppingCart shoppingCart = null;
        if (Objects.nonNull(subCartDTO.getDishId())) {
            //减少的是菜品
             shoppingCart = this.getUserCart(BaseContextUtil.getCurrentId(), subCartDTO.getDishId(),
                    subCartDTO.getDishFlavor(), null);
        } else {
            //减少的是套餐
            shoppingCart = this.getUserCart(BaseContextUtil.getCurrentId(), null, null,
                    subCartDTO.getSetmealId());
        }

        Integer number = shoppingCart.getNumber();
        if (number > 1) {
            //1.菜品数量大于1
            shoppingCart.setNumber(number - 1);
            this.updateById(shoppingCart);
        } else {
            //菜品数量为 1
            this.removeById(shoppingCart.getId());
        }
    }

    /**
     * 清空当前用户的购物车
     * @param
     * @return void
     * @author Guannankun
     * @since 2022/8/28
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cleanCart() {
        this.remove(new LambdaQueryWrapper<ShoppingCart>()
                .eq(ShoppingCart::getUserId, BaseContextUtil.getCurrentId()));
    }

    /**
     * 获取用户购物车中一个菜品或套餐的数据
     * @param userId
     * @param dishId
     * @param dishFlavor
     * @param setmealId
     * @return com.lemon.reggie.pojo.entity.ShoppingCart
     * @author Guannankun
     * @since 2022/8/28
     */
    private ShoppingCart getUserCart(Long userId, Long dishId, String dishFlavor, Long setmealId) {
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<ShoppingCart>()
                .eq(ShoppingCart::getUserId, userId);
        if (Objects.nonNull(dishId)) {
            //菜品
            wrapper.eq(ShoppingCart::getDishId, dishId)
                    .eq(StrUtil.isNotBlank(dishFlavor), ShoppingCart::getDishFlavor, dishFlavor);
        } else {
            //套餐
            wrapper.eq(ShoppingCart::getSetmealId, setmealId);
        }
        return this.getOne(wrapper);
    }

    /**
     * 校验菜品id和套餐id
     * @param dishId
     * @param setMealId
     * @return void
     * @author Guannankun
     * @since 2022/8/23
     */
    /*private void checkDishIdAndSetMealId(Long dishId, Long setMealId) {
        //判断菜品
        if (Objects.isNull(setMealId)) {
            if (Objects.isNull(dishId)) {
                throw new BusinessException("菜品id不能为空！");
            }
        }

        //判断套餐
        if (Objects.isNull(dishId)) {
            if (Objects.isNull(setMealId)) {
                throw new BusinessException("套餐id不能为空！");
            }
        }
    }*/
}
